$NG.AllReady(function (page, { useValuesChange,useDataIndexChange,useUpdateRows,useUpdateRow }) {
    const mstform = $NG.getCmpApi("p_form_car_rental_change_m")
    const dgrid = $NG.getCmpApi("p_form_car_rental_change_d")
    if(page.oType == "add"){
        console.log($NG.getUser());
        const user = $NG.getUser()
        $NG.updateState((updater)=>{
            updater.data.p_form_car_rental_change_m.setProps({
                bill_name:"租车申请变更",
                u_ywlx:"车辆运营费",
                u_app_org:{
                    label:user.orgName,
                    value:user.orgID
                },
                creator:{
                    label:user.userName,
                    value:user.userID
                }
            })
        })
    }
    if(page.oType=='add'){
        $NG.updateState((updater)=>{
            updater.data.p_form_car_rental_change_m.setProps({
                phid_fcur:{
                    label:'人民币',
                    value:1
                },
                exchangerate:1
            })
        })
    }
//项目监听
    useValuesChange(({args})=>{
        console.log(`项目监听`,args);
        getProjectInfo()
        ZfMFilter()
    },"p_form_car_rental_change_m.phid_pc")

    useValuesChange(({args})=>{
        getZcRoi()
    },"p_form_car_rental_change_m.u_car_choose")

    useValuesChange(({args})=>{
        setDataDgrid()
    },"p_form_car_rental_change_m.u_start_dt")

    useValuesChange(({args})=>{
        setDataDgrid()
    },"p_form_car_rental_change_m.u_end_dt")

    // 过滤费用项目
    fyxmFilter()
    function fyxmFilter(){
        $NG.updateUI((updater) =>
            updater.editGrid.p_form_car_rental_change_d.u_cost_pcname.setProps((p) => {
                return {
                    ...p,
                    editor: {
                        ...p.editor,
                        clientSqlFilter: ("phid in('8570000000000352','8570000000000382')")
                    },
                };
            })
        );
    }

    	// 日期监听逻辑
	function setDataDgrid() {
		const _arr = dgrid.getRows();
		const fromStartDate = mstform.getItem("u_start_dt").getValue();
		const fromEndDate = mstform.getItem("u_end_dt").getValue();
        let _count = 0;
		// 日期赋值
		_arr.forEach((item) => {
				item.u_start_dt = fromStartDate;
				item.u_end_dt = fromEndDate;
				item.u_zl_month = dateSubtraction(item.u_end_dt, item.u_start_dt);
                item.u_vat_amt = (Number(item.u_zl_month) || 0) * (Number(item.u_yzvat_amt)||0)
                item.u_amt = (Number(item.u_vat_amt) || 0) * ((1 - Number(item.u_taxrate)||0))
                item.u_taxamount = (Number(item.u_vat_amt)-Number(item.u_amt))
                item.u_tax = (Number(item.u_vat_amt) || 0)-(Number(item.u_amt) || 0)<0?0:(Number(item.u_vat_amt) || 0)-(Number(item.u_amt) || 0)
                _count += Number(item.u_vat_amt) || 0
		});

        $NG.updateState((updater)=>{
            updater.data.p_form_car_rental_change_m.setProps({
                u_cnt_amt:_count
            })
        })
		dgrid.refreshView();
	}

    useUpdateRows(({args})=>{
        
        // 汇总金额
        let _count = 0
        args[0].forEach(item=>{
            _count += Number(item.u_vat_amt) || 0
            if(!item.u_start_dt){
                item.u_start_dt = mstform.getItem("u_start_dt").getValue()
            }
            if(!item.u_end_dt){
                item.u_end_dt = mstform.getItem("u_end_dt").getValue()
            }
            item.u_zl_month = dateSubtraction(item.u_end_dt, item.u_start_dt);
        })
        $NG.updateState((updater)=>{
            updater.data.p_form_car_rental_change_m.setProps({
                u_cnt_amt:_count
            })
        })
        args[0].forEach(item=>{
            const _arr =  item
            //申请含税金额
            _arr.u_vat_amt = (Number(_arr.u_zl_month) || 0) * (Number(_arr.u_yzvat_amt)||0)
            _arr.u_amt = (Number(_arr.u_vat_amt) || 0) * ((1 - Number(_arr.u_taxrate)||0))
            _arr.u_taxamount = (Number(_arr.u_vat_amt)-Number(_arr.u_amt))
            _arr.u_tax = (Number(_arr.u_vat_amt) || 0)-(Number(_arr.u_amt) || 0)<0?0:(Number(_arr.u_vat_amt) || 0)-(Number(_arr.u_amt) || 0)
            _arr.u_phid = generate15DigitNumber()
        })
        dgrid.refreshView()
    },"p_form_car_rental_change_d")
    // 项目信息获取
    getProjectInfo()
     function getProjectInfo(isReturn = false, phid = mstform.getItem("phid_pc").getValue(), fun){
        if(!mstform.getItem("phid_pc").getValue()) return 
        try{
            setTimeout(()=>{
                $NG.execServer("getPtInfoByPhid",{phid: phid}, (res)=>{
                    const _data = JSON.parse(res.data)[0].extendObjects
                    if(res.count == 0) return
                    console.log(`获取项目信息`, _data);
                    if(isReturn){
                        fun(_data)
                    } else {
                        $NG.updateState((updater)=>{
                            updater.data.p_form_car_rental_change_m.setProps({
                                u_pc_no: _data.pc_no, //项目编码
                                u_fycdgs: {
                                    //事业部or组织
                                    value: _data.cwhszz,
									label: _data.cwzz_name,
                                },
                                u_jzgs: {
                                    //事业部or组织
                                    value: _data.org_phid,
                                    label: _data.org_name,
                                },
                                //项目经理
                                u_pc_manager:{
                                    label:_data.project_manager_name,
                                    value:_data.project_manager_phid
                                },
                                u_sqgw: {
                                    //售前顾问
                                    value: _data.user_sqgw_phid,
                                    label: _data.user_sqgw_name,
                                },
                                u_qyzx: {
                                    //区域中心
                                    value: _data.regional_center_phid,
                                    label: _data.regional_center_name,
                                },
                                u_product_line: {
                                    //产品线
                                    value: _data.midwife_phid,
                                    label: _data.midwife_name,
                                },
                                // u_fycdbm: {
                                //     //部门
                                //     value: _data.org_phid,
                                //     label: _data.org_name,
                                // },
                                u_pc_type: {//项目类型
                                    value: _data.type_phid,
                                    label: _data.type_name,
                                },
                            })
                        })
                    }
                })
            },100)
        }catch(err){
            $NG.alert("获取项目信息发生失败请检查~")
        }
    }
    // if(mstform.getItem("u_lease_type").getValue() == "1"){
    //     $NG.updateState((updater)=>{
    //         updater.data.p_form_car_rental_change_m.setProps({
    //             u_lease_type:{
    //                 label:'私车用工',
    //                 value:_data.u_zlfs
    //             },
    //         })
    //     })
    // } else if(mstform.getItem("u_lease_type").getValue() == "2"){
    //     $NG.updateState((updater)=>{
    //         updater.data.p_form_car_rental_change_m.setProps({
    //             u_lease_type:{
    //                 label:'私车用工',
    //                 value:_data.u_zlfs
    //             },
    //         })
    //     })
    // }
    function generate15DigitNumber(arr) {
        if(!arr){
            let str = "";
			// 获取当前时间戳
			let timestamp = Date.now().toString();
			// 如果时间戳不足 15 位，计算需要补充的位数
			let remainingLength = 15 - timestamp.length;
			if (remainingLength > 0) {
				// 生成指定长度的随机数
				let randomPart = "";
				for (let i = 0; i < remainingLength; i++) {
					randomPart += Math.floor(Math.random() * 10);
				}
				// 将时间戳和随机数拼接成 15 位数字
				str = String(timestamp + randomPart);
			} else {
				// 如果时间戳长度超过 15 位，截取前 15 位
				str = String(timestamp.slice(0, 15));
			}
            return str
        }

		arr.forEach((item) => {
			let str = "";
			// 获取当前时间戳
			let timestamp = Date.now().toString();
			// 如果时间戳不足 15 位，计算需要补充的位数
			let remainingLength = 15 - timestamp.length;
			if (remainingLength > 0) {
				// 生成指定长度的随机数
				let randomPart = "";
				for (let i = 0; i < remainingLength; i++) {
					randomPart += Math.floor(Math.random() * 10);
				}
				// 将时间戳和随机数拼接成 15 位数字
				str = String(timestamp + randomPart);
			} else {
				// 如果时间戳长度超过 15 位，截取前 15 位
				str = String(timestamp.slice(0, 15));
			}
			if (!item.u_phid) {
				item.u_phid = str;
				dgrid1.refreshView();
				dgrid2.refreshView();
				dgrid3.refreshView();
				dgrid4.refreshView();
			}
		});
	}
     // 获取原租车信息
     function getZcRoi(){
        console.log(mstform.getItem("u_car_choose").getValue());
        if(!mstform.getItem("u_car_choose").getValue()) return
        $NG.execServer("getZcRoi",{phid:mstform.getItem("u_car_choose").getValue()},function(res){
            console.log(`租车原信息获取`,res);
            if(res.count == 0)return 
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater)=>{
                updater.data.p_form_car_rental_change_m.setProps({
                    u_old_zcsq_no:_data.bill_no,
                    u_start_dt:_data.u_start_dt,
                    u_end_dt:_data.u_end_dt,
                    u_ori_start_dt:_data.u_start_dt,
                    u_ori_end_dt:_data.u_end_dt,
                    u_rent_com:_data.u_rent_com,
                    u_cnt_amt_ori:_data.u_cnt_amt,
                    u_source_phid:_data.mphid,
                    // u_lease_type:{
                    //     label:'私车用工',
                    //     value:_data.u_zlfs
                    // },
                    u_old_apply:{
                        label:_data.creator_exname,
                        value:_data.creator
                    },
                    u_fycdbm:{
                        label:_data.u_fycdbm_exname,
                        value:_data.u_fycdbm
                    }
                })
            })
            if(_data.u_zlfs == "1"){
                $NG.updateState((updater)=>{
                    updater.data.p_form_car_rental_change_m.setProps({
                        u_lease_type:{
                            label:'对公租赁',
                            value:_data.u_zlfs
                        },
                    })
                })
            } else if(_data.u_zlfs == "2"){
                $NG.updateState((updater)=>{
                    updater.data.p_form_car_rental_change_m.setProps({
                        u_lease_type:{
                            label:'私车用工',
                            value:_data.u_zlfs
                        },
                    })
                })
            }

        })
    }
    ZfMFilter()
        function ZfMFilter() {
            $NG.updateUI((updater, state) => {
                console.log('过滤参数检查', updater);
                updater.fieldSetForm.p_form_car_rental_change_m.u_car_choose.setProps({
                    onBeforeOpen: async () => {
                        var phid_pc = $NG.getCmpApi('p_form_car_rental_change_m').getItem('phid_pc').getValue();
                        if (!phid_pc) {
                            $NG.alert("请先选择项目");
                            return false;
                        } else {
                            return true;
                        }
                    },
                    ...(!!$NG.getCmpApi('p_form_car_rental_change_m').getItem('phid_pc').getValue() && {
                        clientSqlFilter: {
                            phid_pc: $NG.getCmpApi('p_form_car_rental_change_m').getItem('phid_pc').getValue()
                        }
                    }),
                });
            });
        }
    // 根据费用编码获取费用名称
    function getFynameByFyno(phid,fun){
        $NG.execServer("getFynameByFyno", {phid},function(res){
            console.log(res);
            if(res.count ==0||!phid)return 
            const _data = JSON.parse(res.data)[0].extendObjects
            fun(_data)
        })
    }
            //月数计算
            function dateSubtraction(date1, date2) {
                const d1 = new Date(date1);
                const d2 = new Date(date2);
            
                if (isNaN(d1.getTime()) || isNaN(d2.getTime())) {
                    return null;
                }
            
                const timeDiff = Math.abs(d1 - d2);
                const daysDiff = timeDiff / (1000 * 60 * 60 * 24);
                return (daysDiff / 30).toFixed(2)
            }
});

